import {getStorage} from "../components/utils";
import {transmitFormData} from "../../network/servers";
import {CheckTokenParam} from "./types";

const storage = getStorage();

let interval;

let checkTokenParam: CheckTokenParam = {
  appId: "",
  schoolId: "",
  schoolUrl: "",
  systemId: "",
  onTokenRefresh: () => {}
};

export const enableTokenCheck = (param: CheckTokenParam) => {
  checkTokenParam = param
  interval = setInterval(() => {
    checkToken()
  }, 1000 * 10);
}

const checkToken = () => {
  const paramData = {
    AppID: checkTokenParam.appId,
    Param: JSON.stringify({
      token: storage.get("token"),
      method: "TokenCheck",
      params: "E43",
    }),
    SchoolID: checkTokenParam.schoolId,
    Url: checkTokenParam.schoolUrl + "/UserMgr/Login/Api/Login.ashx",
    UserID: storage.get("account"),
  };

  transmitFormData(paramData).then((data) => {
    const dataInfo = JSON.parse(data.data.Content);
    if (!dataInfo.data.result) {
      clearTokenCheckInterval()
      console.log("Token失效了，开始重新更新Token");
      // that.userRelogin();
      reLogin()
    } else {
      console.log("万幸,Token还活着");
    }
  });
}

export const clearTokenCheckInterval = () => {
  clearInterval(interval)
}

export const reLogin = () => {
  const userId = storage.get("account");

  const paramString = userId + "|" + storage.get("md5Pwd") + `|${checkTokenParam.systemId}|` + 6 + "|||";

  const paramData = {
    AppID: checkTokenParam.appId,
    Param: JSON.stringify({
      method: "Login",
      params: paramString
    }),
    SchoolID: checkTokenParam.schoolId,
    Url: checkTokenParam.schoolUrl + "/UserMgr/Login/Api/Login.ashx",
    UserID: userId,
  };
  transmitFormData(paramData).then((data) => {
    if (data.data.Content) {
      try {
        const dataInfo = JSON.parse(data.data.Content);
        if (dataInfo.data.result == 1) {
          const newToken = dataInfo.data.token;
          //更新token并且，通知token更新
          storage.set("token", newToken)
          if(checkTokenParam.onTokenRefresh){
            checkTokenParam.onTokenRefresh(newToken)
          }

          console.log("已重新获取Token,新token:" + newToken);
          clearTokenCheckInterval()
          enableTokenCheck(checkTokenParam)
        } else {
          console.log("重新获取Token失败");
        }
      } catch (error) {}
    } else {
      console.log("后台错误了");
    }
  });
}
